package com.songshuai.sales.client.service.impl;


import com.songshuai.sales.client.dao.*;

import com.songshuai.sales.client.dto.request.frontsop.*;
import com.songshuai.sales.client.dto.response.frontsop.ArticleSopResDto;
import com.songshuai.sales.client.dto.response.frontsop.ListResDto;
import com.songshuai.sales.client.feign.PanguApiClient;
import com.songshuai.sales.client.service.FrontSopService;
import com.songshuai.webapi.baseapi.dto.pangu.request.salesclient.CustomerListReqDto;
import com.songshuai.webapi.baseapi.dto.pangu.response.salesclient.CustomerInfoDto;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.enumerations.sales.CustomerActionEnum;
import com.songshuai.webapi.baseapi.enumerations.sales.error.SopError;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.model.sales.*;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.DateUtil;
import com.songshuai.webapi.baseapi.utils.PageUtil;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.baseapi.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FrontSopServiceImpl implements FrontSopService{

    @Autowired
    private SopMapper sopMapper;
    @Autowired
    private LabelSopRelationMapper labelSopRelationMapper;
    @Autowired
    private PushRecordMapper pushRecordMapper;
    @Autowired
    private SnowFlakeUtil snowFlakeUtil;
    @Autowired
    private CustomerActionMapper customerActionMapper;

    @Autowired
    private PanguApiClient panguApiClient;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;
    @Autowired
    private LabelMapper labelMapper;


    //查找主子标签（包含自身）--mysql版
    private List<Integer> findSubLabelIds(Integer labelId){

        if(null == labelId){
            return null;
        }

        List<Integer> all = null;
        String str = sopMapper.selectSubLabelSql(labelId);
        if(StringUtils.isEmpty(str)){
            return all;
        }

        all = new ArrayList<Integer>();
        str = str.substring(1);
        String[] allStr = str.split(",");
        for(String s:allStr){
            all.add(Integer.parseInt(s));
        }
        return all;
    }

    //返回子标签列表
    private List<String> getLabelList(String labelId){

        if(labelId == null){
            return null;
        }

        Label label =  labelMapper.selectByPrimaryKey(labelId);
        if(label == null){
            return null;
        }
        List<String> result = null;

        //是否为组标签
        if("0".equals(label.getParentId())){
            Label labelObj = new Label();
            labelObj.setParentId(labelId);
            List<Label> labels = labelMapper.selectByEntityList(labelObj);
            if(labels == null || labels.size() == 0){
                return null;
            }
            result = labels.stream().map(item->item.getLabelId()).collect(Collectors.toList());

        }else{
            result = new ArrayList<String>();
            result.add(labelId);
        }
        return result;
    }

    @Override
    public PageUtil showList(BaseParmDto<ListReqDto> request) {

        try{

            //主子标签
            //List<Integer> labelList = this.findSubLabelIds(request.getParam().getLabelId());
            request.getParam().setLabelIds(this.getLabelList(request.getParam().getLabelId()));

            //Integer count = sopMapper.selectSopListCount(request.getParam());
            //设置分页
            PageUtil page = new PageUtil(request.getPageIndex(), request.getPageSize(), 0);
            request.getParam().setStart(page.getStart());
            request.getParam().setEnd(page.getEnd());

            List<ListResDto> lists = sopMapper.selectSopList(request.getParam());


            page.setLists(lists);
            return page;

        }catch (Exception e) {
            log.error("api/front/sop/showList", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }


    }

    /**
     * customerList
     */
     public QueryResponse customerList(BaseParmDto<CustomerListReqDto> request){

         if(request.getParam() == null){
             throw new BusinessException(ResultStatus.ERROR_INVALID_ARGUMENT.getErrorMsg(), ResultStatus.FAILOfficial);
         }
         if(StringUtils.isBlank(request.getParam().getSearchStr())){
             request.getParam().setSearchStr("");
         }

         try{
             QueryResponse<List<CustomerInfoDto>> result = panguApiClient.getCustomerList(request);
             if(result.getCode() == 0){
                 List<CustomerInfoDto> lists = this.relationWechat(result.getData());
                 return QueryResponse.setResData(lists);
             }else{
                 return result;
             }
         }catch (Exception e) {
             log.error("api/front/sop/customerList", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
         }
    }

    /*客户关联微信*/
    private List<CustomerInfoDto> relationWechat(List<CustomerInfoDto> lists){

        if(lists == null || lists.size() <= 0){ return null; }
        List<String> list = new ArrayList<String>();
        for(CustomerInfoDto customerInfoDto:lists){
            list.add(customerInfoDto.getCustomerId());
        }
        List<CustomerInfo> customers = customerInfoMapper.selectCustomerListByKeys(list);
        if(customers == null || customers.size() <= 0){
            return lists;
        }

        Map<String, Boolean> map = new HashMap<String, Boolean>();
        for(CustomerInfo customer:customers){
            map.put(customer.getUserId(),true);
        }

        for(CustomerInfoDto customerInfoDto:lists){
            if(map.get(customerInfoDto.getCustomerId())!=null){
                customerInfoDto.setIsBinding("1");
            }

        }

        return lists;
    }

    /**
     * 添加浏览记录
     * Integer type (1:浏览,2:分享,3:点赞,4:评价)
     * String sopId 浏览资源
     * String userId 浏览人
     */
    private String addSopActionRecord(Integer type, String sopId, String userId){

        CustomerAction entity = new CustomerAction();
        entity.setId(snowFlakeUtil.nextId());
        entity.setSopId(sopId);
        entity.setAction(type);
        entity.setActionUser(userId);
        entity.setLookTime(new Date());
        customerActionMapper.insert(entity);

        return entity.getId();
    }

    @Override
    public ArticleSopResDto articleSop(ArticleSopReqDto articleSopReqDto) {

        //参数校验
        if( StringUtils.isEmpty(articleSopReqDto.getSopId()) ){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }

        Sop sopCheck = sopMapper.selectByPrimaryKey(articleSopReqDto.getSopId());
        if(sopCheck == null || sopCheck.getIsDelete().intValue() == 1){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        try{

            //浏览+1
//            sopCheck.setClickNum(sopCheck.getClickNum().intValue()+1);
//            sopMapper.updateByPrimaryKey(sopCheck);

            //添加浏览记录
            //String viewId = this.addSopActionRecord(CustomerActionEnum.View.getCode(), articleSopReqDto.getSopId(), articleSopReqDto.getCurrentUserId());

            ArticleSopResDto articleSopResDto = new ArticleSopResDto();
            PropertiesUtil.copyProperties(sopCheck, articleSopResDto);
            articleSopResDto.setCreateTime(sopCheck.getCreateTime());
            articleSopResDto.setUpdateTime(sopCheck.getUpdateTime());
            //articleSopResDto.setViewId(viewId);

            //标签属性
            LabelSopRelation labelSopRelation = new LabelSopRelation();
            labelSopRelation.setSopId(articleSopReqDto.getSopId());
            List<Label> labels =  labelSopRelationMapper.selectLabelsForSopId(labelSopRelation);

            articleSopResDto.setLabels(labels);
            return articleSopResDto;

        }catch (Exception e) {
            log.error("api/front/sop/articleSop", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }

    }

    @Override
    @Transactional
    public Map sendSop(SendReqDto sendReqDto) {


        //参数校验
        if( StringUtils.isEmpty(sendReqDto.getSopId()) ){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }


        if(sendReqDto.getReciveUsers() == null || sendReqDto.getReciveUsers().size() == 0){
            throw new BusinessException(SopError.ERROR_SOP_RECIVEUSERS_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }

//        if( StringUtils.isEmpty(sendReqDto.getReciveUsers()) ){
//            throw new BusinessException(SopError.ERROR_SOP_RECIVEUSERS_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
//        }
//
//        String[] reciveUsers = sendReqDto.getReciveUsers().split(",");
//        if(reciveUsers == null || reciveUsers.length == 0){
//            throw new BusinessException(SopError.ERROR_SOP_RECIVEUSERS_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
//        }


        Sop sopCheck = sopMapper.selectByPrimaryKey(sendReqDto.getSopId());
        if(sopCheck == null || sopCheck.getIsDelete() == 1){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }

        Map map = new HashMap();

        try{

            Date time = new Date();
            PushRecord pushRecord = null;

            //未绑定微信数量
            int noWechatNum = 0;
            for(ReciveUserReqDto reciveUser:sendReqDto.getReciveUsers()){

                if(!"1".equals(reciveUser.getIsWechat())){
                    noWechatNum++;
                    continue;
                }
                pushRecord = new PushRecord();
                pushRecord.setId(snowFlakeUtil.nextId());
                pushRecord.setSopId(sopCheck.getSopId());
                pushRecord.setSopName(sopCheck.getTitle());
                pushRecord.setPushTime(time);
                pushRecord.setPushUser(sendReqDto.getCurrentUserId());
                pushRecord.setReciveUser(reciveUser.getReciveUserId());
                pushRecord.setReciveUserName(reciveUser.getReciveUserName());
                pushRecord.setReciveUserMobile(reciveUser.getReciveUserMobile());
                pushRecord.setIsOpen(0);
                pushRecordMapper.insertSelective(pushRecord);
            }

            map.put("noWechatNum",noWechatNum);
            map.put("wechatNum",sendReqDto.getReciveUsers().size() - noWechatNum);

            return map;

        }catch (Exception e) {
            log.error("api/front/sop/sendSop", e);
            throw new BusinessException(ResultStatus.ERROR_UPDATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }
    }

    @Override
    public void goodSop(GoodReqDto goodReqDto) {

        //参数校验
        if( StringUtils.isEmpty(goodReqDto.getSopId()) ){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }

        Sop sopCheck = sopMapper.selectByPrimaryKey(goodReqDto.getSopId());
        if(sopCheck == null || sopCheck.getIsDelete() == 1){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        try{
            sopCheck.setGoodNum(sopCheck.getGoodNum().intValue()+1);
            sopMapper.updateByPrimaryKey(sopCheck);

            //点赞记录
            this.addSopActionRecord(CustomerActionEnum.good.getCode(),goodReqDto.getSopId(),goodReqDto.getCurrentUserId());

        }catch (Exception e) {
            log.error("api/front/sop/goodSop", e);
            throw new BusinessException(ResultStatus.ERROR_UPDATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }


    }




    @Override
    public void closeView(CloseViewReqDto closeViewReqDto) {

        //参数校验
        if( StringUtils.isEmpty(closeViewReqDto.getViewId()) ){
            throw new BusinessException(SopError.ERROR_SOP_VIEWID_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }

        CustomerAction customerAction = customerActionMapper.selectByPrimaryKey(closeViewReqDto.getViewId());
        if(customerAction == null){
            throw new BusinessException(SopError.ERROR_SOP_VIEWID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        try{

            Date startTime = customerAction.getLookTime();
            Date endTime = new Date();
            int second = DateUtil.calcSecond(startTime, endTime);
            customerAction.setBrowseTime(second);
            customerActionMapper.updateByPrimaryKey(customerAction);

        }catch (Exception e) {
            log.error("api/front/sop/closeView", e);
            throw new BusinessException(ResultStatus.ERROR_UPDATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }

    }


}
